package it.nard.controller;

import it.nard.constant.Constant;
import it.nard.listener.ControlDocumentListener;
import it.nard.persistence.dao.LatteinentrataMapper;
import it.nard.persistence.model.Allevatori;
import it.nard.persistence.model.Latteinentrata;
import it.nard.persistence.model.LatteinentrataExample;
import it.nard.persistence.model.RmozzarellaExample;
import it.nard.sourceframes.AllevatoriPnl;
import it.nard.sourceframes.LatteInEntrataPnl;
import it.nard.sourceframes.LatteInGiacenzaPnl;
import it.nard.sourceframes.MainFrame;
import it.nard.sourceframes.RMozzarellaPnl;

import java.awt.Color;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

import org.apache.ibatis.session.SqlSession;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
import org.jdesktop.swingx.decorator.HighlighterFactory;

public class LatteInEntrataController  extends BasicController{

	/**
	 * 
	 */
	private static final long serialVersionUID = 980399986779921835L;


	public static final String LATTE_ENTRATA = "latteEntrata";
	
	
	
	private HashMap<String, String> cisternaHm = new HashMap<String, String>();
	
	
	
	
	public LatteInEntrataController(){
		super("Latte in Entrata", null);
		clearCisternaHm();
	}
	
	private void clearCisternaHm(){
		cisternaHm.put(Constant.CISTERNE[0], Constant.CISTERNE[0]+":");
		cisternaHm.put(Constant.CISTERNE[1], Constant.CISTERNE[1]+":");
		cisternaHm.put(Constant.CISTERNE[2], Constant.CISTERNE[2]+":");
		cisternaHm.put(Constant.CISTERNE[3], Constant.CISTERNE[3]+":");
	}
	
	
	public void select (MouseEvent mevent){
		
		try{
			this.selectedRow =  ((LatteInEntrataPnl)controlPnl).getJTable0().convertRowIndexToModel( ((LatteInEntrataPnl)controlPnl).getJTable0().getSelectedRow());
		}catch(Exception e ){	
		}
		if(this.selectedRow==-1)
			return;
				
		  Latteinentrata latte = (Latteinentrata) objList.get(selectedRow);
		  try {
				((LatteInEntrataPnl)controlPnl).getJTextField0().setDate(SDF_4_DB.parse(latte.getDatain().toString()));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 ((LatteInEntrataPnl)controlPnl).getJTextField1().setText(latte.getAcidita());
		 ((LatteInEntrataPnl)controlPnl).getJTextField7().setText(latte.getCaricoserb1());
		 ((LatteInEntrataPnl)controlPnl).getJTextField6().setText(latte.getCaricoserb2());
		 ((LatteInEntrataPnl)controlPnl).getJTextField8().setText(latte.getCaricoserb3());
		 ((LatteInEntrataPnl)controlPnl).getJTextField9().setText(latte.getCaricoserb4());
		 ((LatteInEntrataPnl)controlPnl).getJTextField4().setText(latte.getCongelamento());
		 ((LatteInEntrataPnl)controlPnl).getJTextArea0().setText(latte.getProvenienza());
		 ((LatteInEntrataPnl)controlPnl).getJTextField2().setText(latte.getTemperatura());
		 ((LatteInEntrataPnl)controlPnl).getJTextField3().setText(latte.getVendita());
		 ((LatteInEntrataPnl)controlPnl).getJTextField5().setText(latte.getTrasfsenzastock());
	
		String valueCombo = latte.getProvenienza().substring(0, latte.getProvenienza().indexOf(":"));
		 ((LatteInEntrataPnl)controlPnl).getJComboBox0().setSelectedItem(valueCombo);
		
	
		mainFrame.sendMessage("Selezionato Latte in Entrata.", MainFrame.OK_MESSAGE);

		
	}

	public List<Latteinentrata> retriveListFromDates(Date dt1, Date dt2){
		 List<Latteinentrata> out = new ArrayList<Latteinentrata>();
		Integer dataStart = null;
		Integer dataStop = null;
		

		try{
			String tempStart = SDF_4_DB.format( dt1);
			
			
			dataStart = new Integer(tempStart);
			
			String tempStop = SDF_4_DB.format( dt2);
			
			dataStop = new Integer(tempStop);
			
			
			
		}catch(Exception e ){
			e.printStackTrace();
		}
		
		LatteinentrataExample lee = new LatteinentrataExample();
		
		lee.createCriteria().andDatainBetween(dataStart, dataStop);
		lee.setOrderByClause("datain");
		
		
		
		SqlSession sqlSession = MainController.getSqlSessionFactory().openSession();
		
		out = sqlSession.getMapper(LatteinentrataMapper.class).selectByExampleWithBLOBs(lee);
		
		sqlSession.close();
		return out;
		
	}
	
	public void onDateSelect(){
		
		DefaultTableModel dtm = (DefaultTableModel) ((LatteInEntrataPnl)controlPnl).getJTable0().getModel();
		dtm.getDataVector().removeAllElements();
		dtm.setNumRows(0);
		dtm.fireTableDataChanged();
		
		
		Integer dataStart = null;
		Integer dataStop = null;
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		
		try{
			String tempStart = sdf.format( ((LatteInEntrataPnl)controlPnl).getJTextField0().getDate());
			tempStart = tempStart.concat("01");
			
			dataStart = new Integer(tempStart);
			
			String tempStop = sdf.format( ((LatteInEntrataPnl)controlPnl).getJTextField0().getDate());
			tempStop = tempStop.concat("31");
			
			dataStop = new Integer(tempStop);
			
			
			
		}catch(Exception e ){
			e.printStackTrace();
		}
		
		LatteinentrataExample lee = new LatteinentrataExample();
		
		lee.createCriteria().andDatainBetween(dataStart, dataStop);
		lee.setOrderByClause("datain");
		
		
		
		SqlSession sqlSession = MainController.getSqlSessionFactory().openSession();
		
		objList = sqlSession.getMapper(LatteinentrataMapper.class).selectByExampleWithBLOBs(lee);
		
		sqlSession.close();
		
		
		mainFrame.sendMessage("Selezionato Latte in Entrata.", MainFrame.OK_MESSAGE);
		 
		 
		dtm = (DefaultTableModel) ((LatteInEntrataPnl)controlPnl).getJTable0().getModel();
		Iterator<Latteinentrata> iter = (Iterator<Latteinentrata>)objList.iterator();
		while(iter.hasNext()){
			Latteinentrata latte = iter.next();
			String provenienza = latte.getProvenienza().substring(0, latte.getProvenienza().indexOf(":"));
			SimpleDateFormat sdfRow = new SimpleDateFormat("dd/MM/yyyy");
			
			try {
				dtm.addRow(new String[]{sdfRow.format(SDF_4_DB.parse(String.valueOf(latte.getDatain()))),provenienza,latte.getVendita(), latte.getCongelamento(), latte.getTrasfsenzastock(), latte.getCaricoserb1(), latte.getCaricoserb2(), latte.getCaricoserb3(), latte.getCaricoserb4()});

				
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	
	}
	
	public void onChangeCisterna(){
		 ((LatteInEntrataPnl)controlPnl).getJTextArea0().setText("");
		 ((LatteInEntrataPnl)controlPnl).getJTextArea0().setText(cisternaHm.get( ((LatteInEntrataPnl)controlPnl).getJComboBox0().getSelectedItem()));
	}
	
	public void delete (){
		
		SqlSession sqlSession = MainController.getSqlSessionFactory().openSession();
		
		sqlSession.getMapper(LatteinentrataMapper.class).deleteByPrimaryKey(((Latteinentrata)(objList.get(selectedRow))).getId());
	
		sqlSession.commit();
		
		
		 try {
			mainFrame.sendMessage("Cancellato Latte in Entrata.", MainFrame.OK_MESSAGE);
		 } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		 }
		
		DefaultTableModel dtm = (DefaultTableModel) ((LatteInEntrataPnl)controlPnl).getJTable0().getModel();
		try{
			dtm.removeRow(selectedRow);
		}catch(Exception e ){}
		
		
		clearPnl();
		sqlSession.close();
	}
	
	public void insert (){
		
		SqlSession sqlSession = MainController.getSqlSessionFactory().openSession();
		
		Latteinentrata latte = new Latteinentrata();
		
		if(selectedRow!=-1  || ((LatteInEntrataPnl)controlPnl).getJTable0().getModel().getRowCount()!=0){
			
			latte = (Latteinentrata)this.objList.get(this.selectedRow);
		}
		
		latte.setAcidita( ((LatteInEntrataPnl)controlPnl).getJTextField1().getText().trim());
		latte.setCaricoserb1( ((LatteInEntrataPnl)controlPnl).getJTextField7().getText().trim());
		latte.setCaricoserb2( ((LatteInEntrataPnl)controlPnl).getJTextField6().getText().trim());
		latte.setCaricoserb3( ((LatteInEntrataPnl)controlPnl).getJTextField8().getText().trim());
		latte.setCaricoserb4( ((LatteInEntrataPnl)controlPnl).getJTextField9().getText().trim());
		latte.setCongelamento( ((LatteInEntrataPnl)controlPnl).getJTextField4().getText().trim());
		latte.setProvenienza( ((LatteInEntrataPnl)controlPnl).getJTextArea0().getText());
		latte.setTemperatura( ((LatteInEntrataPnl)controlPnl).getJTextField2().getText().trim());
		latte.setTrasfsenzastock( ((LatteInEntrataPnl)controlPnl).getJTextField5().getText().trim());
		latte.setVendita( ((LatteInEntrataPnl)controlPnl).getJTextField3().getText().trim());
		
		LatteinentrataExample lee = new LatteinentrataExample();
		lee.createCriteria().andDatainEqualTo(Integer.parseInt(SDF_4_DB.format( ((LatteInEntrataPnl)controlPnl).getJTextField0().getDate())));
		
		if(selectedRow==-1  || ((LatteInEntrataPnl)controlPnl).getJTable0().getModel().getRowCount()==0){
		
					
					Integer dataIn = null;
					try{
						dataIn = new Integer(SDF_4_DB.format( ((LatteInEntrataPnl)controlPnl).getJTextField0().getDate()));
					}catch(Exception e ){
						e.printStackTrace();
					}
					latte.setDatain(dataIn);
					
					
				
					sqlSession.getMapper(LatteinentrataMapper.class).insert(latte);
					sqlSession.commit();
					
					
					mainFrame.sendMessage("Inserito Latte in Entrata.", MainFrame.OK_MESSAGE);
					 
					
					objList = sqlSession.getMapper(LatteinentrataMapper.class).selectByExampleWithBLOBs(lee);
					
					DefaultTableModel dtm = (DefaultTableModel) ((LatteInEntrataPnl)controlPnl).getJTable0().getModel();
					
					String provenienza = latte.getProvenienza().substring(0, latte.getProvenienza().indexOf(":"));
					SimpleDateFormat sdfRow = new SimpleDateFormat("dd/MM/yyyy");
					
					try {
						dtm.addRow(new String[]{sdfRow.format(SDF_4_DB.parse(String.valueOf(latte.getDatain()))),provenienza,latte.getVendita(), latte.getCongelamento(), latte.getTrasfsenzastock(), latte.getCaricoserb1(), latte.getCaricoserb2(), latte.getCaricoserb3(), latte.getCaricoserb4()});

						
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					clearPnl();
					sqlSession.close();
				
					
		
		}
		else{
			
			sqlSession.getMapper(LatteinentrataMapper.class).updateByPrimaryKeyWithBLOBs(latte);
			
			sqlSession.commit();
			
			mainFrame.sendMessage("Modificato Latte in Entrata.", MainFrame.OK_MESSAGE);
			
			objList = sqlSession.getMapper(LatteinentrataMapper.class).selectByExampleWithBLOBs(lee);
			
			DefaultTableModel dtm = (DefaultTableModel) ((LatteInEntrataPnl)controlPnl).getJTable0().getModel();
			
			
			
			
				
			String provenienza = latte.getProvenienza().substring(0, latte.getProvenienza().indexOf(":"));		
			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
			
			try {
				dtm.setValueAt(sdf.format(SDF_4_DB.parse(String.valueOf(latte.getDatain()))),selectedRow, 0);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			dtm.setValueAt(provenienza,selectedRow, 1);
			dtm.setValueAt(latte.getVendita(),selectedRow, 2);
			dtm.setValueAt(latte.getCongelamento(),selectedRow, 3);
			dtm.setValueAt(latte.getTrasfsenzastock(),selectedRow, 4);
			dtm.setValueAt(latte.getCaricoserb1(),selectedRow, 5);
			dtm.setValueAt(latte.getCaricoserb2(),selectedRow, 6);
			dtm.setValueAt(latte.getCaricoserb3(),selectedRow, 7);
			dtm.setValueAt(latte.getCaricoserb4(),selectedRow, 8);
			

			clearPnl();	
		}
		
		clearPnl();
	}
	
	public   LatteInEntrataPnl getMainPanel(){
		
			
			if( controlPnl==null){
				controlPnl = new  LatteInEntrataPnl(this);
			
			
			
			
			
			 JXTable theTable =  ((LatteInEntrataPnl)controlPnl).getJTable0();
			 theTable.addHighlighter(HighlighterFactory.createAlternateStriping(Color.getHSBColor(229,229,229), Color.getHSBColor(208, 208, 208))); 
			 AutoCompleteDecorator.decorate( ((LatteInEntrataPnl)controlPnl).getJComboBox0());
			 
			 BasicController.tableDocumentListener.addTableListener( ((LatteInEntrataPnl)controlPnl).getJTextField10(),  ((LatteInEntrataPnl)controlPnl).getJTable0());
			 
			 theTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			 
			 ControlDocumentListener cdl = BasicController.controlDocumentListener;
			
			 ArrayList<JButton> listButton = new ArrayList<JButton>();
			 listButton.add( ((LatteInEntrataPnl)controlPnl).getJButton0());
			 listButton.add( ((LatteInEntrataPnl)controlPnl).getJButton1());
			
			 
			 ArrayList<JTextField> listMandatory = new ArrayList<JTextField>();
			 listMandatory.add( ((LatteInEntrataPnl)controlPnl).getJTextField1());
			 listMandatory.add( ((LatteInEntrataPnl)controlPnl).getJTextField2());
			 
			 ArrayList<JTextField> listNumeric = new ArrayList<JTextField>();
			 listNumeric.add( ((LatteInEntrataPnl)controlPnl).getJTextField1());
			 listNumeric.add( ((LatteInEntrataPnl)controlPnl).getJTextField2());
			 listNumeric.add( ((LatteInEntrataPnl)controlPnl).getJTextField3());
			 listNumeric.add( ((LatteInEntrataPnl)controlPnl).getJTextField4());
			 listNumeric.add( ((LatteInEntrataPnl)controlPnl).getJTextField5());
			 listNumeric.add( ((LatteInEntrataPnl)controlPnl).getJTextField6());
			 listNumeric.add( ((LatteInEntrataPnl)controlPnl).getJTextField7());
			 listNumeric.add( ((LatteInEntrataPnl)controlPnl).getJTextField8());
			 listNumeric.add( ((LatteInEntrataPnl)controlPnl).getJTextField9());
			 
			 cdl.addControlElement(ControlDocumentListener.MANDATORY_FIELD,  ((LatteInEntrataPnl)controlPnl).getJTextField1(), listButton,listMandatory, listNumeric);
			 cdl.addControlElement(ControlDocumentListener.MANDATORY_FIELD,  ((LatteInEntrataPnl)controlPnl).getJTextField2(), listButton,listMandatory, listNumeric);
			 cdl.addControlElement(ControlDocumentListener.NUMBER_FIELD,  ((LatteInEntrataPnl)controlPnl).getJTextField1(), listButton, listMandatory, listNumeric);
			 cdl.addControlElement(ControlDocumentListener.NUMBER_FIELD,  ((LatteInEntrataPnl)controlPnl).getJTextField2(), listButton, listMandatory, listNumeric);
			 cdl.addControlElement(ControlDocumentListener.NUMBER_FIELD,  ((LatteInEntrataPnl)controlPnl).getJTextField3(), listButton, listMandatory, listNumeric);
			 cdl.addControlElement(ControlDocumentListener.NUMBER_FIELD,  ((LatteInEntrataPnl)controlPnl).getJTextField4(), listButton, listMandatory, listNumeric);
			 cdl.addControlElement(ControlDocumentListener.NUMBER_FIELD,  ((LatteInEntrataPnl)controlPnl).getJTextField5(), listButton, listMandatory, listNumeric);
			 cdl.addControlElement(ControlDocumentListener.NUMBER_FIELD,  ((LatteInEntrataPnl)controlPnl).getJTextField6(), listButton, listMandatory, listNumeric);
			 cdl.addControlElement(ControlDocumentListener.NUMBER_FIELD,  ((LatteInEntrataPnl)controlPnl).getJTextField7(), listButton, listMandatory, listNumeric);
			 cdl.addControlElement(ControlDocumentListener.NUMBER_FIELD,  ((LatteInEntrataPnl)controlPnl).getJTextField8(), listButton, listMandatory, listNumeric);
			 cdl.addControlElement(ControlDocumentListener.NUMBER_FIELD,  ((LatteInEntrataPnl)controlPnl).getJTextField9(), listButton, listMandatory, listNumeric);
			 
			}
			
			List<Allevatori> listAllevatori = MainController.getAllevatoriController().retriveobjList();			
			Iterator<Allevatori> iter = listAllevatori.iterator();
			clearCisternaHm();
			while(iter.hasNext()){
				Allevatori elem = iter.next();
				if(elem.getCisterna()!=null && !elem.getCisterna().trim().equals(""))
					cisternaHm.put(elem.getCisterna(), cisternaHm.get(elem.getCisterna())+elem.getNumidentificativo()+" - ");	
			}
			onChangeCisterna();
			
			onDateSelect();
			return  ((LatteInEntrataPnl)controlPnl);
	}

	

	@Override
	public String getControllerCode() {
		return LATTE_ENTRATA;
	}

	@Override
	public void clearPnl() {
		  ((LatteInEntrataPnl)controlPnl).getJTextField0().setDate(new Date());
		  ((LatteInEntrataPnl)controlPnl).getJComboBox0().setSelectedIndex(0);
		  ((LatteInEntrataPnl)controlPnl).getJTextArea0().setText("");
		  ((LatteInEntrataPnl)controlPnl).getJTextField1().setText("");
		  ((LatteInEntrataPnl)controlPnl).getJTextField2().setText("");
		  ((LatteInEntrataPnl)controlPnl).getJTextField3().setText("");
		  ((LatteInEntrataPnl)controlPnl).getJTextField4().setText("");
		  ((LatteInEntrataPnl)controlPnl).getJTextField5().setText("");
		  ((LatteInEntrataPnl)controlPnl).getJTextField6().setText("");
		  ((LatteInEntrataPnl)controlPnl).getJTextField7().setText("");
		  ((LatteInEntrataPnl)controlPnl).getJTextField8().setText("");
		  ((LatteInEntrataPnl)controlPnl).getJTextField9().setText("");
		 onChangeCisterna();
	}
	
	
	
	
	
	
	
}
